//
//  AppDelegate.m
//  MyProject
//
//  Created by yanjiaming on 17/3/10.
//  Copyright © 2017年 yanjiaming. All rights reserved.
//

#import "AppDelegate.h"
#import "YJMNavigationController.h"
#import "EntryViewController.h"
#import "CashHomeViewController.h"
#import "MessageHomeVC.h"
#import <Hyphenate/Hyphenate.h>
#import "MySelfVC.h"
#import "TabbarViewController.h"
#import "NewFeatureViewController.h"
#import "LoginViewController.h"
#import "SelectRolesViewController.h"
#import "NSUDManager.h"
#import "AppDelegate+XG.h"
#import "ExpectedIndustryVC.h"
#import "RolesViewController.h"
#import "InAppRageIAPHelper.h"
#import "CertificationViewController.h"
#import "MOBShareSDKHelper.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//微信SDK头文件
#import "WXApi.h"
#import "JobCertificationViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "FindPeopleViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

-(void)registerShare{
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeWechat)
                                        ]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {

             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx1b19c99f92cb5e78"
                                       appSecret:@"5f060c6700656c2d75e48a20ff193123"];
                 break;
            
             default:
                 break;
         }
     }];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
     [[SKPaymentQueue defaultQueue] addTransactionObserver:[InAppRageIAPHelper sharedHelper]];
    
    [self registerShare];
    
    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    [self loadXGFinishLaunchingWithOptions:launchOptions];
    EMOptions *options = [EMOptions optionsWithAppkey:@"1171180508253732#taijie"];
    options.apnsCertName = @"istore_dev";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    [self gotoHome];
    
    
    // 判断是否显示新特性
    NSString *firstStartKey = [NSString stringWithFormat:@"FirstStart_%@", [Tool getSoftVersion]];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:firstStartKey] == nil || [[[NSUserDefaults standardUserDefaults] objectForKey:firstStartKey] isEqualToString:@"0"]) {
        self.window.rootViewController = [[NewFeatureViewController alloc] init];
        [self.window makeKeyAndVisible];
    } else {
        // 判断是否是首次登录， 首次登录需登录、注册
        UserModel *user = [NSUDManager currentUser];
        if (user) {
            [[EMClient sharedClient] loginWithUsername:user.userId
                                              password:user.userId
                                            completion:^(NSString *aUsername, EMError *aError) {
                                                if (!aError) {
                                                    NSLog(@"登录成功");
                                                } else {
                                                    NSLog(@"登录失败");
                                                }
                                            }];
            if ([user.role isEqualToString:@"0"] || [user.role integerValue] == 0) {
                RolesViewController *roles = [[RolesViewController alloc] init];
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:roles];

                self.window.rootViewController = nav;
            } else {
                [self gotoHome];
//                TabbarViewController *tabbar = [TabbarViewController sharedTBVC];
////                if ([user.role isEqualToString:@"1"] || [user.role integerValue] == 1) {
////                    tabbar.selectedIndex = 0;
////                } else {
////                    tabbar.selectedIndex = 1;
////                }
//                self.window.rootViewController = tabbar;
            }

        } else {
            self.window.rootViewController = [[LoginViewController alloc] init];
        }

        [self.window makeKeyAndVisible];
    }
    
    
//    self.window.rootViewController = [[JobCertificationViewController alloc] init];
//
//    JobCertificationViewController *certificate = [[JobCertificationViewController alloc] init];
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:certificate];
//    self.window.rootViewController = nav;
//    [self.window makeKeyAndVisible];

  
   

    return YES;
}
-(void)gotoLogin{
    self.window.rootViewController = [[LoginViewController alloc] init];
    [self.window makeKeyAndVisible];
}
-(void)gotoHome{
    
    FindPeopleViewController *find = [[FindPeopleViewController alloc]init];
    YJMNavigationController *findNav = [[YJMNavigationController alloc]initWithRootViewController:find];
    findNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"找人" image:IMAGE(@"ic_找人_unselect") selectedImage:IMAGE(@"ic_找人_select")];
    
    
    EntryViewController *homePage = [[EntryViewController alloc]init];
    YJMNavigationController *homeNav = [[YJMNavigationController alloc]initWithRootViewController:homePage];
    //    homeNav.navigationBarHidden = YES;
    homeNav.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"职位" image:IMAGE(@"ic_Frontpage_Unselected") selectedImage:IMAGE(@"ic_Frontpage_Selected")];
    
    
    //    CashHomeViewController *homePage1 = [[CashHomeViewController alloc]init];
    //    YJMNavigationController *homeNav1 = [[YJMNavigationController alloc]initWithRootViewController:homePage1];
    //    homeNav1.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"变现" image:IMAGE(@"ic_Cash_Unselected") selectedImage:IMAGE(@"ic_Cash_Selected")];
    
    MessageHomeVC *homePage2 = [[MessageHomeVC alloc]init];
    YJMNavigationController *homeNav2 = [[YJMNavigationController alloc]initWithRootViewController:homePage2];
    homeNav2.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"消息" image:IMAGE(@"ic_news_Unselected") selectedImage:IMAGE(@"ic_news_Selected")];
    
    
    MySelfVC *chatController = [[MySelfVC alloc]init];
    YJMNavigationController *homeNav3 = [[YJMNavigationController alloc]initWithRootViewController:chatController];
    homeNav3.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"我的" image:IMAGE(@"ic_me_Unselected") selectedImage:IMAGE(@"ic_me_Selected")];
    
    
    self.tabbarController = [[UITabBarController alloc]init];
    self.tabbarController.tabBar.tintColor = UIColorFromRGB(0xffffff);
    self.tabbarController.delegate = self;
    [self.tabbarController.tabBar setBarTintColor:kBlackColor];
    self.tabbarController.viewControllers = [NSArray arrayWithObjects:findNav,homeNav,homeNav2,homeNav3, nil];
    self.window.rootViewController = self.tabbarController;
    [self.window makeKeyAndVisible];
    [YJMSendRequest postDataWithParameters:@{} url:@"user/getUserMessageUnreadCount" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1)
        {
            NSInteger total = [result[@"data"][@"MESSAGE_TYPE_CANDIDATE"] integerValue] + [result[@"data"][@"MESSAGE_TYPE_INCUMBENT"] integerValue] +[result[@"data"][@"MESSAGE_TYPE_SYSTEM"] integerValue] ;
            if (total>  0) {
                [homeNav2.tabBarItem setBadgeValue:[NSString stringWithFormat:@"%zd",total]];
            }else{
                [homeNav2.tabBarItem setBadgeValue:nil];
            }
        }else{
            
        }
        
    }];
    
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    if ([viewController isKindOfClass:[YJMNavigationController class]]) {
        YJMNavigationController *nav = (YJMNavigationController *)viewController;
        for (NSInteger i = 0; i<nav.yjm_viewControllers.count; i++) {
            SaintiLog(@"%@",nav.yjm_viewControllers[i]);
            if ([nav.yjm_viewControllers[i] isKindOfClass:[MessageHomeVC class]]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMessage" object:nil];
                
            }
        }
    }
}
-(void)loginAgain{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient]  logout:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [NSUDManager setCurrentUser:nil];
            
            KUSERDEFAULTS;
            [defaults removeObjectForKey:@"currentUser"];
            [defaults synchronize];
            [self gotoLogin];
        });
        
    });
}
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo{
    SaintiLog(@"%@",userInfo);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:[InAppRageIAPHelper sharedHelper]];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }else if ([url.host isEqualToString:@"platformId=wechat"]){
        [WXApi handleOpenURL:url delegate:self];
    }
    
    return  YES;
}

- (void)onReq:(BaseReq *)req
{
    NSLog(@"--->%s wxapi onreq:%@",__func__,req);
}

- (void)onResp:(BaseResp *)resp
{
    NSLog(@"--->%s wxapi onresp:%@",__func__,resp);
}

@end
